package com.rickpan.service;

import com.rickpan.entity.User;
import com.rickpan.repository.FileInfoRepository;
import com.rickpan.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 存储空间修复服务
 * 用于修复存储空间统计不一致的问题
 */
@Service
public class StorageRepairService {

    private static final Logger logger = LoggerFactory.getLogger(StorageRepairService.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private FileInfoRepository fileInfoRepository;

    /**
     * 修复单个用户的存储空间统计
     */
    @Transactional
    public Map<String, Object> repairUserStorageUsage(Long userId) {
        logger.info("开始修复用户存储空间统计: userId={}", userId);

        // 获取用户信息
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在: " + userId));

        // 计算实际存储使用量（只统计未删除的文件）
        Long actualStorageUsed = fileInfoRepository.calculateUserStorageUsage(userId);
        if (actualStorageUsed == null) {
            actualStorageUsed = 0L;
        }

        // 获取当前记录的存储使用量
        Long currentStorageUsed = user.getStorageUsed();
        if (currentStorageUsed == null) {
            currentStorageUsed = 0L;
        }

        // 计算差异
        Long difference = actualStorageUsed - currentStorageUsed;

        // 更新用户存储使用量
        user.setStorageUsed(actualStorageUsed);
        userRepository.save(user);

        Map<String, Object> result = new HashMap<>();
        result.put("userId", userId);
        result.put("username", user.getUsername());
        result.put("beforeRepair", currentStorageUsed);
        result.put("afterRepair", actualStorageUsed);
        result.put("difference", difference);
        result.put("differenceFormatted", formatFileSize(Math.abs(difference)));
        result.put("isFixed", !difference.equals(0L));

        logger.info("用户存储空间统计修复完成: userId={}, 修复前={}, 修复后={}, 差异={}",
                   userId, currentStorageUsed, actualStorageUsed, difference);

        return result;
    }

    /**
     * 修复所有用户的存储空间统计
     */
    @Transactional
    public Map<String, Object> repairAllUsersStorageUsage() {
        logger.info("开始修复所有用户存储空间统计");

        List<User> allUsers = userRepository.findAll();
        int totalUsers = allUsers.size();
        int fixedUsers = 0;
        long totalDifference = 0;

        for (User user : allUsers) {
            try {
                Map<String, Object> userResult = repairUserStorageUsage(user.getId());
                Boolean isFixed = (Boolean) userResult.get("isFixed");
                if (isFixed) {
                    fixedUsers++;
                    Long difference = (Long) userResult.get("difference");
                    totalDifference += Math.abs(difference);
                }
            } catch (Exception e) {
                logger.error("修复用户存储空间统计失败: userId={}", user.getId(), e);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("totalUsers", totalUsers);
        result.put("fixedUsers", fixedUsers);
        result.put("totalDifference", totalDifference);
        result.put("totalDifferenceFormatted", formatFileSize(totalDifference));

        logger.info("所有用户存储空间统计修复完成: 总用户数={}, 修复用户数={}, 总差异={}",
                   totalUsers, fixedUsers, totalDifference);

        return result;
    }

    /**
     * 检查用户存储空间统计是否正确
     */
    public Map<String, Object> checkUserStorageUsage(Long userId) {
        logger.info("检查用户存储空间统计: userId={}", userId);

        // 获取用户信息
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在: " + userId));

        // 计算实际存储使用量
        Long actualStorageUsed = fileInfoRepository.calculateUserStorageUsage(userId);
        if (actualStorageUsed == null) {
            actualStorageUsed = 0L;
        }

        // 获取当前记录的存储使用量
        Long currentStorageUsed = user.getStorageUsed();
        if (currentStorageUsed == null) {
            currentStorageUsed = 0L;
        }

        // 计算差异
        Long difference = actualStorageUsed - currentStorageUsed;
        boolean isConsistent = difference.equals(0L);

        Map<String, Object> result = new HashMap<>();
        result.put("userId", userId);
        result.put("username", user.getUsername());
        result.put("currentStorageUsed", currentStorageUsed);
        result.put("actualStorageUsed", actualStorageUsed);
        result.put("difference", difference);
        result.put("differenceFormatted", formatFileSize(Math.abs(difference)));
        result.put("isConsistent", isConsistent);
        result.put("needsRepair", !isConsistent);

        logger.info("用户存储空间统计检查完成: userId={}, 一致性={}, 差异={}",
                   userId, isConsistent, difference);

        return result;
    }

    /**
     * 格式化文件大小
     */
    private String formatFileSize(long bytes) {
        if (bytes == 0) return "0 B";
        
        String[] units = {"B", "KB", "MB", "GB", "TB"};
        int unitIndex = 0;
        double size = bytes;
        
        while (size >= 1024 && unitIndex < units.length - 1) {
            size /= 1024;
            unitIndex++;
        }
        
        return String.format("%.2f %s", size, units[unitIndex]);
    }
}
